/*The MIT License

Copyright (c) <1/27/2011> <erick.difiore>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

package com.d4a5.mapping.esri
{
	import com.esri.ags.Graphic;
	import com.esri.ags.renderers.SimpleRenderer;
	import com.esri.ags.symbol.SimpleFillSymbol;
	import com.esri.ags.symbol.SimpleLineSymbol;
	import com.esri.ags.symbol.SimpleMarkerSymbol;
	import com.esri.ags.symbol.Symbol;
	
	import mx.collections.ArrayCollection;
	
	public class wmeGradientRenderer extends wmeRenderer
	{
		
		public static const calcPctLinear:int = 0;
		public static const calcPctLog:int = 1;
		
		public var calculatePercentageMethod:int = 0;

		public var attribute:String;
		public var divideAttributeBy:String;
		public var multipleBy:Number = Number.NaN;
		
		protected var _infos:Array;
		
		protected var _outOfRangeSymbol:Symbol;
		protected var _noRangeSymbol:Symbol;
		
		
		public var complexCalculationFunction:Function;
		public var calculatedValueFieldName:String;
		
		public function wmeGradientRenderer( attribute:String = null, defaultSymbol:Symbol = null , infos:Array = null )
		{
			super();
			
			this.defaultSymbol = defaultSymbol;
			this.attribute = attribute;
			this.infos = infos;
		}
		
		public function get outOfRangeSymbol() : Symbol {
			return (this._outOfRangeSymbol) ? this._outOfRangeSymbol : this.defaultSymbol;
		}
		public function set outOfRangeSymbol( value:Symbol ) : void {
			this._outOfRangeSymbol = value;
		}
		
		public function get noRangeSymbol() : Symbol {
			return (this._noRangeSymbol) ? this._noRangeSymbol : this.defaultSymbol;
		}
		public function set noRangeSymbol( value:Symbol ) : void {
			this._noRangeSymbol = value;
		}
		
		
		
		public function get infos() : Array {
			return this._infos;
		}
		public function set infos( value:Array ) : void {
			this._infos = value;
		}
		
		protected function getAttributeValue( graphic:Graphic , attributeName:String ) : Number {
			var parts:Array = attributeName.split(/\./);
			var numParts:int = parts.length;
			
			var obj:Object = graphic.attributes;
			try{
				for( var j:int = 0; j < numParts; j++ ){
					obj = obj[ parts[j] ];
				} 
			}
			catch( error:Error ){
				return Number.NaN;
			}
			return Number( obj )
		}
		
		override public function getSymbol(graphic:Graphic):Symbol {
			var value:Number;
			
			if( this.calculatedValueFieldName ){
				graphic.attributes[this.calculatedValueFieldName] = Number.NaN;
			}
			
			try{
				value = this.getAttributeValue( graphic , this.attribute );
				
				if( this.complexCalculationFunction ){
					value = this.complexCalculationFunction( this , graphic );
					
					if( this.calculatedValueFieldName ){
						graphic.attributes[this.calculatedValueFieldName] = value;
					}
				}
				else if( this.divideAttributeBy ){
					value = value / this.getAttributeValue( graphic , this.divideAttributeBy );
					
					if( this.calculatedValueFieldName ){
						graphic.attributes[this.calculatedValueFieldName] = value;
					}
				}
				else if( isNaN( this.multipleBy ) == false ){
					value *= this.multipleBy;
				}
				
				
				if( isNaN( value ) ){
					return this.defaultSymbol;
				}
			}
			catch( error:Error ){
				return this.defaultSymbol;
			}
			
			if( this._infos.length > 1 ){
				this._infos.sortOn( "value" , Array.NUMERIC );
				

				var minInfo:wmeGradientInfo = this._infos[0];
				var maxInfo:wmeGradientInfo = this._infos[this._infos.length-1];
				if( value < minInfo.value || value > maxInfo.value ){
					return this.outOfRangeSymbol;
				}
				
				maxInfo = null;
				var length:int = this._infos.length;
				for( var i:int = 1; i < length; i++ ){
					maxInfo = this._infos[i]; 
					if( value <= maxInfo.value ){
						return this.createNewSymbol( value , minInfo , maxInfo ); 
					}
					minInfo = maxInfo;
				}
			}
			
			return this.defaultSymbol;
		}
		
		public function GetSymbolFromData( value:Number ) : Symbol {
			
			if( this._infos.length > 1  ){
				this._infos.sortOn( "value" , Array.NUMERIC );
				
				if( isNaN( value ) ){
					throw new Error( "GetSymbolInfo: Value is NaN" );
				}
				
				
				var minInfo:wmeGradientInfo = this._infos[0];
				var maxInfo:wmeGradientInfo = this._infos[this._infos.length-1];
				if( value < minInfo.value || value > maxInfo.value ){
					throw new Error( "GetSymbolInfo: Out of Range" );
				}
				
				maxInfo = null;
				var length:int = this._infos.length;
				for( var i:int = 1; i < length; i++ ){
					maxInfo = this._infos[i]; 
					if( value <= maxInfo.value ){
						return this.createNewSymbol( value , minInfo , maxInfo ); 
					}
					minInfo = maxInfo;
				}
				
				throw new Error( "GetSymbolInfo: Out of Range" );
			}
			else{
				throw new Error( "GetSymbolInfo: Not Enough Infos" );
			}
			
			return null;
		}
		
		protected function createNewSymbol( value:Number  , minInfo:wmeGradientInfo , maxInfo:wmeGradientInfo ) : Symbol {
			var min:Number = minInfo.value;
			var max:Number = maxInfo.value;
			if( min == max ){
				return this.noRangeSymbol;
			}
			
			var minSym:Symbol = minInfo.symbol;
			var maxSym:Symbol = maxInfo.symbol;
			
			var pct:Number;
			if( this.calculatePercentageMethod == wmeGradientRenderer.calcPctLog ){
				value = (value == 0) ? .000000001 : value;
				min = (min == 0) ?  .000000001 : min;
				max = (max == 0) ?  .000000001 : max;
				pct =  (Math.log(value) - Math.log(min)) / (Math.log(max) - Math.log(min))
			}
			else{
				pct = ( value - min ) / ( max - min );
			}
			
			
			if( minSym is SimpleFillSymbol && maxSym is SimpleFillSymbol ){
				var minSfs:SimpleFillSymbol = minSym as SimpleFillSymbol;
				var maxSfs:SimpleFillSymbol = maxSym as SimpleFillSymbol;
				
				var wFs:wmeFillSymbol = new wmeFillSymbol();
				wFs.style = ( pct < .5 ) ? minSfs.style : maxSfs.style;
				wFs.color = this.calculateColor( pct , minSfs.color , maxSfs.color );
				wFs.alpha = (pct * (maxSfs.alpha - minSfs.alpha)) + minSfs.alpha;
				
				
				if( minSfs.outline && maxSfs.outline ){
					wFs.outline = new wmeLineSymbol();
					
					wFs.outline.style = ( pct < .5 ) ? minSfs.outline.style : maxSfs.outline.style;
					wFs.outline.width = (pct * (maxSfs.outline.width - minSfs.outline.width)) + minSfs.outline.width;
					wFs.outline.color = this.calculateColor( pct ,  minSfs.outline.color , maxSfs.outline.color );
					wFs.outline.alpha = (pct * (maxSfs.outline.alpha - minSfs.outline.alpha)) + minSfs.outline.alpha;
				}
				else if( minSfs && pct < .5 ){
					wFs.outline = minSfs.outline;
				}
				else if( maxSfs && pct >= .5 ){
					wFs.outline = maxSfs.outline;
				}
				return wFs;
			}
			else if( minSym is SimpleMarkerSymbol && maxSym is SimpleMarkerSymbol ){
				var minSms:SimpleMarkerSymbol = minSym as SimpleMarkerSymbol;
				var maxSms:SimpleMarkerSymbol = maxSym as SimpleMarkerSymbol;
				
				var wSms:wmeMarkerSymbol = new wmeMarkerSymbol();
				wSms.style = ( pct < .5 ) ? minSms.style : maxSms.style;
				wSms.size = (pct * (maxSms.size - minSms.size)) + minSms.size;
				wSms.color = this.calculateColor( pct , minSms.color , maxSms.color );
				wSms.alpha = (pct * (maxSms.alpha - minSms.alpha)) + minSms.alpha;
				wSms.xoffset = (pct * (maxSms.xoffset - minSms.xoffset)) + minSms.xoffset;
				wSms.yoffset = (pct * (maxSms.yoffset - minSms.yoffset)) + minSms.yoffset;
				wSms.angle = (pct * (maxSms.angle - minSms.angle)) + minSms.angle;
				
				
				if( minSms.outline && maxSms.outline ){
					wSms.outline = new wmeLineSymbol();
					
					wSms.outline.style = ( pct < .5 ) ? minSms.outline.style : maxSms.outline.style;
					wSms.outline.width = (pct * (maxSms.outline.width - minSms.outline.width)) + minSms.outline.width;
					wSms.outline.color = this.calculateColor( pct ,  minSms.outline.color , maxSms.outline.color );
					wSms.outline.alpha = (pct * (maxSms.outline.alpha - minSms.outline.alpha)) + minSms.outline.alpha;
				}
				else if( minSms && pct < .5 ){
					wSms.outline = minSms.outline;
				}
				else if( maxSms && pct >= .5 ){
					wSms.outline = maxSms.outline;
				}
				return wSms;
			}
			else if( minSym is SimpleLineSymbol && maxSym is SimpleLineSymbol ){
				var minSls:SimpleLineSymbol = minSym as SimpleLineSymbol;
				var maxSls:SimpleLineSymbol = maxSym as SimpleLineSymbol;
				
				var wLs:wmeLineSymbol = new wmeLineSymbol();
				wLs.style = ( pct < .5 ) ? minSls.style : maxSls.style;
				wLs.width = (pct * (maxSls.width - minSls.width)) + minSls.width;
				wLs.color = this.calculateColor( pct ,  minSls.color , maxSls.color );
				wLs.alpha = (pct * (maxSls.alpha - minSls.alpha)) + minSls.alpha;
			
				return wLs;
			}
			
			return this.defaultSymbol;
		}
		
		protected function calculateColor( pct:Number , min:int , max:int ) : uint {
			var minColor:Object = { color : min , r : (min & 0xff0000) >> 16 , g : (min & 0xff00) >> 8 , b : (min & 0xff) };
			var maxColor:Object = { color : max , r : (max & 0xff0000) >> 16 , g : (max & 0xff00) >> 8 , b : (max & 0xff) };
			
			var differences:Object = new Object();
			differences.r = maxColor.r - minColor.r;
			differences.g = maxColor.g - minColor.g;
			differences.b = maxColor.b - minColor.b;
			
			var r:int = int((Number(differences.r) * Number(pct))+ Number(minColor.r));
			var g:int = int((Number(differences.g) * Number(pct))+ Number(minColor.g));
			var b:int = int((Number(differences.b) * Number(pct))+ Number(minColor.b));
			
			var color:uint = (r<<16)+(g<<8)+b;
			return color;
		}
		
		
		
	}
}